package com.maple.base.base

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.kongqw.network.monitor.NetworkMonitorManager
import com.kongqw.network.monitor.enums.NetworkState
import com.kongqw.network.monitor.interfaces.NetworkMonitor
import com.maple.base.widget.loading.LoadingDialog
import com.maple.utils.ext.toVisible
import com.maple.utils.util.Event
import com.maple.utils.util.EventBusUtils
import com.maple.utils.util.NetworkUtil
import com.maple.utils.util.ToastUtils
import com.zackratos.ultimatebarx.ultimatebarx.statusBarOnly
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseActivity : AppCompatActivity(), IView {
    /// 传递bundle 数据 Key
    private val KEY_BUNDLE_DATA: String = "BUNDLE_DATA"

    private var loadingDialog: LoadingDialog? = null

    /// 布局
    abstract fun getLayoutId(): Int

    abstract fun initData(savedInstanceState: Bundle?): Unit

    /// 是否使用 event bus
    open fun hasUsedEventBus(): Boolean = false
    // 是否使用状态栏
    open fun hasStatusBarMode(): Boolean = false
    // 是否使用 监听网络状态变化
    open fun hasNetworkState(): Boolean = false
    open fun onBeforeCreate(savedInstanceState: Bundle?) {}

    open fun initView(savedInstanceState: Bundle?) {}

    override fun onCreate(savedInstanceState: Bundle?) {
        onBeforeCreate(savedInstanceState)
        super.onCreate(savedInstanceState)
        setContentLayout()
        if (hasUsedEventBus()) {
            EventBusUtils.register(this)
        }
        if (hasStatusBarMode()) {
            setStatusBarMode()
        }
        initView(savedInstanceState)
        initData(savedInstanceState)
        if(hasNetworkState()) {
            NetworkMonitorManager.getInstance().register(this)
            val type = if(NetworkUtil.netWorkType() == NetworkUtil.NetType.NET_4G) {
                 NetworkState.CELLULAR
            } else if(NetworkUtil.netWorkType() == NetworkUtil.NetType.WIFI) {
                NetworkState.WIFI
            } else {
                NetworkState.NONE
            }
            onNetWorkChange(type)
        }
    }

    open fun setStatusBarMode(color: Int = com.maple.res.R.color.toolbar_bg, fitWindow: Boolean = true, light: Boolean = true) {
        // 只需要设置状态栏，不需要设置导航栏
        statusBarOnly {
            // 布局是否侵入状态栏（true 不侵入，false 侵入）
            this.fitWindow = fitWindow
            // 状态栏背景颜色（资源 id）
            this.colorRes = color
            // light模式：状态栏字体 true: 灰色，false: 白色 Android 6.0+
            this.light = light
        }
    }

    /// 设置布局文件(BaseActivity 和 BaseViewActivity分别重写)
    open fun setContentLayout() {
        setContentView(getLayoutId())
    }

    open fun showLoading() {
        if (loadingDialog == null) {
            loadingDialog = LoadingDialog(this)
        }
        loadingDialog?.run {
            if (!this.isShowing) this.show()
        }
    }

    /// 关闭 loading
    open fun dismissLoading() {
        loadingDialog?.run {
            if (isShowing) {
                runBlocking {
                    delay(500L)
                }
                dismiss()
            }
        }
    }

    /// 获取封装 bundle
    open fun getBundle(): Bundle? {
        return this.intent?.getBundleExtra(KEY_BUNDLE_DATA)
    }

    /***
     * 打开新的页面
     * @param clazz 新页面
     * @param bundle 传递bundle 数据,非必填
     * @param isFinish 是否关闭当前页面 默认不关闭
     */
    open fun onStartActivity(
        clazz: Class<out Activity?>,
        bundle: Bundle? = null,
        isFinish: Boolean = false,
        isPrevent: Boolean = false,
    ) {
        if (isPrevent && ActivityUtils.isActivityExistsInStack(clazz)) {
            return
        }
        this.startActivity(Intent(this, clazz).apply {
            bundle?.let {
                this.putExtra(KEY_BUNDLE_DATA, it)
            }
        })
        if (isFinish) this.onFinish()
    }


    /**
     * 接收到普通的Event
     * 封装MAIN线程模式，子类可重写 onEvnetBusReceive,
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun <T> onEventBusReceive(event: Event<T>?) {
        if (event != null) {
            onEventBusDispense(event)
        }
    }

    /**
     * 接收到粘性的Event
     * 封装MAIN线程模式，子类可重写 onStickyEvnetBusReceive,
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    open fun <T> onStickyEventBusReceive(event: Event<T>?) {
        if (event != null) {
            onStickyEventBusDispense(event)
        }
    }

    /**
     * 子类重写onEventBusDispense，处理接收到的普通事件
     */
    open fun <T> onEventBusDispense(event: Event<T>) {}

    /**
     * 子类重写onStickyEventBusDispense，处理接收到的粘性事件
     */
    open fun <T> onStickyEventBusDispense(event: Event<T>) {}


    @NetworkMonitor
    fun onNetWorkStateChange(networkState: NetworkState) {
        runOnUiThread {
            onNetWorkChange(networkState)
        }
    }

    open fun onNetWorkChange(networkState: NetworkState) {}

    fun hideKeyboard() {
        if (KeyboardUtils.isSoftInputVisible(this)) {
            KeyboardUtils.hideSoftInput(this)
        }
    }

    /***
     * 关闭页面
     */
    open fun onFinish() {
        this.finish()
    }

    /**
     * toast
     * @param s 显示内容
     */
    open fun showToast(s: String?) {
        if (this.lifecycle.currentState.isAtLeast(Lifecycle.State.CREATED)) {
            runOnUiThread {
                ToastUtils.showToast(s)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if(hasNetworkState()) {
            NetworkMonitorManager.getInstance().unregister(this)
        }
        if (hasUsedEventBus()) {
            EventBusUtils.unregister(this)
        }
    }
}